<?php

namespace Modules\Category\Entities;

use Modules\Core\Entities\BaseEntity as Model;

class Category extends Model
{
    protected $guarded = [];
    protected $table = 'categories';

    static public $resourceName = '分类';

    public function sub_categories()
    {
        return $this->hasMany('\Modules\Category\Entities\Category', 'parent_id')->orderBy('list_weight', 'desc');
    }

    public function scopeLevel($query, $level)
    {
        return $query->where('level', $level);
    }

    public function scopeType($query, $type)
    {
        return $query->where('type', $type);
    }

    public function products()
    {
        return $this->belongsToMany('\Modules\Product\Entities\Product', 'category_relations', 'category_id', 'target_id')->wherePivot('type', 'product');
    }

    public function onstock_products()
    {
        return $this->products()->onStock();
    }

    public function boxes()
    {
        return $this->belongsToMany('\Modules\Box\Entities\Box', 'category_relations', 'category_id', 'target_id')->wherePivot('type', 'box');
    }

    public function onstock_boxes()
    {
        return $this->boxes()->onStock();
    }
}
